package com.we.risk.smsInfo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.we.utils.CommonTimeTools;
import com.we.utils.ParamCheck;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.we.risk.smsInfo.SmsType.*;

public class AdmSmsInfoLocalCmp {
    public static final String RELEASEPROP = "risk/plist/adm_plist_kfk_prod.properties";
    public static final String PROPSETS = "risk/plist/plist.properties";
    public static Logger LOG = LoggerFactory.getLogger(AdmSmsInfoLocalCmp.class);

    public static final String SPLITWORD = "#";
    public static final String DATEFORMAT = "yyyy-MM-dd";
    public static final String MSGTYPE = "HFQ_UPLOAD_SMS_REPORT_RECORD";
    public static final String INPUTKEYBY = "userKey";
    public static final String OUTPUTKEY = "user_key";
    public static final String HTTPTIMESTAMP = "httpTimestamp";
    public static final String CAPTIME = "capture_time";
    public static final String LABELOUTPUTIME = "label_output_time";
    public static final String INJOBID = "jobID";
    public static final String OUTJOBID = "job_id";
    public static final String SMSLIST = "sms_list";
    public static final int JSONSIZE = 4;

    public static void main(String[] args) throws IOException {
        try {
            long start = System.currentTimeMillis();
            String file =
                    "/Users/jk/Downloads/风控标签需求/实时需求/短信/cmp/1123/411063ff96fd820375fa2fb46d252523.json";
            String keyProp = "/Users/jk/Downloads/风控标签需求/实时需求/短信/sms_stage1st.prop";
            String value = FileUtils.readFileToString(new File(file));
            List<String> lines = FileUtils.readLines(new File(keyProp));
            SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
            JSONObject inputJson = filterSmsInfoMsg(value);
            if (inputJson.size() == JSONSIZE
                    && inputJson.containsKey(OUTPUTKEY)
                    && inputJson.containsKey(SMSLIST)) {
                HashMap<String, SmsCategory> d7Map = initODMap();
                HashMap<String, SmsCategory> d30Map = initMap();
                HashMap<String, SmsCategory> d60Map = initODMap();
                HashMap<String, SmsCategory> d90Map = initMap();
                HashMap<String, SmsCategory> d180Map = initMap();
                HashMap<String, SmsCategory> d365Map = initMap();

                String userKey = inputJson.getString(OUTPUTKEY);
                String jobId = inputJson.getString(OUTJOBID);
                Long capTime = inputJson.getLong(CAPTIME);
                JSONArray smsArray = inputJson.getJSONArray(SMSLIST);
                int size = smsArray.size();
                for (int i = 0; i < size; i++) {
                    JSONObject smsInfo = (JSONObject) smsArray.get(i);
                    ParamCheck.isNull(smsInfo, "smsInfo");

                    //                    String body = smsInfo.getString("body");
                    //                    if(body != null && body.contains("消费9元失败")) {
                    //                        System.out.println("smsInfo: " + smsInfo);
                    //                    }

                    SmsInfoBasic smsInfoBasic =
                            SmsInfoBasic.constructSmsinfoBasic(smsInfo, capTime, sdf);
                    if (smsInfoBasic != null) {
                        long recvTime = smsInfoBasic.getRecvTime();
                        Integer dateDiff = CommonTimeTools.dateDiff(capTime, recvTime, sdf);
                        //                        System.out.println("smsInfoBasic: " +
                        // smsInfoBasic);
                        if (dateDiff <= 7) {
                            smsLoanOdProcess(smsInfoBasic, d7Map, sdf, dateDiff);
                        }

                        if (dateDiff <= 60) {
                            smsLoanOdProcess(smsInfoBasic, d60Map, sdf, dateDiff);
                        }

                        if (dateDiff <= 30) {
                            //                            if(smsInfoBasic.getIsBank() == 1 &&
                            // smsInfoBasic.getIsWeekend() == 1) {
                            //                                System.out.println("smsInfo: " +
                            // smsInfo);
                            //                                if(smsInfoBasic.getBankRemainAmt() !=
                            // null) {
                            //                                    System.out.println("" +
                            // smsInfoBasic.getRecvTime() + " " + smsInfoBasic.getBankRemainAmt());
                            //                                }
                            //                            }
                            smsCateLabelProcess(smsInfoBasic, d30Map, sdf, dateDiff);
                        }
                        if (dateDiff <= 90) {
                            if (smsInfoBasic.getIsRecv() == 1 && smsInfoBasic.getIsRead() == 0) {
                                System.out.println("d90smsInfo: " + smsInfo);
                            }
                            smsCateLabelProcess(smsInfoBasic, d90Map, sdf, dateDiff);
                        }
                        if (dateDiff <= 180) {
                            //                            if(smsInfoBasic.getIsBank() == 1 &&
                            // smsInfoBasic.getIsCashOut() == 1) {
                            //                                System.out.println("smsInfo: " +
                            // smsInfo);
                            ////                                if(smsInfoBasic.getIsWeekend() != 1
                            // && smsInfoBasic.getBankRemainAmt() != null) {
                            ////                                {
                            ////                                    System.out.println("##D30
                            // getCashOutAmt: " + smsInfoBasic.getCashOutAmt());
                            ////                                }
                            //                            }
                            smsCateLabelProcess(smsInfoBasic, d180Map, sdf, dateDiff);
                        }
                        if (dateDiff <= 365) {
                            //                            if(smsInfoBasic.getIsCrdt() == 1 &&
                            // smsInfoBasic.isWeekend != 1 ) {
                            ////                                System.out.println("##loan_30
                            // smsInfo: " + smsInfo);
                            //                                if(smsInfoBasic.crdtAmt != null) {
                            //                                    System.out.println("##loan_30
                            // smsInfo: " + smsInfo);
                            //                                    System.out.println("" +
                            // smsInfoBasic.getRecvTime() + " " + smsInfoBasic.getCrdtAmt());
                            ////                                    System.out.println("#d365
                            // crdtAmt: " + smsInfoBasic.getCrdtAmt());
                            //                                }
                            //                            }
                            smsCateLabelProcess(smsInfoBasic, d365Map, sdf, dateDiff);
                        }
                    } else {
                        LOG.warn(
                                "flatMap constructSmsinfoBasic returns null, inputJson: "
                                        + smsInfo);
                    }
                }
                JSONObject outJson = new JSONObject();
                outJson.put(OUTPUTKEY, userKey);
                outJson.put(OUTJOBID, jobId);
                outJson.put(CAPTIME, capTime);
                collectLabelJsonObject(d7Map, outJson, "d7");
                collectLabelJsonObject(d30Map, outJson, "d30");
                collectLabelJsonObject(d60Map, outJson, "d60");
                collectLabelJsonObject(d90Map, outJson, "d90");
                collectLabelJsonObject(d180Map, outJson, "d180");
                collectLabelJsonObject(d365Map, outJson, "d365");
                long labelOutPutTime = System.currentTimeMillis();
                outJson.put(LABELOUTPUTIME, labelOutPutTime);
                System.out.println("res size: " + outJson.size());
                System.out.println("outJson: " + outJson.toString());
                System.out.println("Cost time: " + (System.currentTimeMillis() - start));
                //                JSONObject resJson = new JSONObject();
                //                for (String line: lines) {
                //                    if(outJson.containsKey(line)){
                //                        resJson.put(line, outJson.get(line));
                //                    } else {
                //                        resJson.put(line, null);
                //                    }
                //                }
                //                System.out.println("res size: " + resJson.size());
                //                System.out.println("outJson: " +
                // resJson.toString(SerializerFeature.WriteMapNullValue));
            }

        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
            LOG.error("Exception: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void collectLabelJsonObject(
            HashMap<String, SmsCategory> map, JSONObject inputJson, String diffDays) {
        if (!map.isEmpty() && inputJson != null) {
            Set<String> keySet = map.keySet();
            for (String key : keySet) {
                //                if(diffDays.equals("d30") && key.equals(BANK)) {
                //                    LOG.warn("debug");
                //                }
                SmsCategory smsCategory = map.get(key);
                if (smsCategory != null) {
                    smsCategory.smsCalcLable(diffDays);
                    HashMap<String, Object> resMap = smsCategory.getResMap();
                    inputJson.putAll(resMap);
                }
            }
        }
    }

    private static HashMap<String, SmsCategory> initMap() {
        HashMap<String, SmsCategory> map = new HashMap<>();

        map.put(BASE, new SmsCategory(BASE));
        map.put(TELE, new SmsCategory(TELE));
        map.put(EXPS, new SmsCategory(EXPS));
        map.put(SERV, new SmsCategory(SERV));
        map.put(PAYT, new SmsCategory(PAYT));
        map.put(BANK, new SmsCategory(BANK));
        map.put(CRDT, new SmsCategory(CRDT));
        map.put(LOAN, new SmsCategory(LOAN));
        map.put(OD, new SmsCategory(OD));

        return map;
    }

    private static HashMap<String, SmsCategory> initODMap() {
        HashMap<String, SmsCategory> map = new HashMap<>();
        map.put(OD, new SmsCategory(OD));

        return map;
    }

    private static void smsCateLabelProcess(
            SmsInfoBasic basicInfo,
            HashMap<String, SmsCategory> cateMap,
            SimpleDateFormat sdf,
            Integer diffDays) {
        try {
            cateMap.get(BASE).smsBaseProcess(basicInfo, sdf, diffDays);
            int isRecv = basicInfo.getIsRecv();
            String body_name = basicInfo.getBody_name();

            if (isRecv == 1 && body_name != null && body_name.length() >= 2) {
                if (basicInfo.getIsTelecom() == 1 && cateMap.get(TELE) != null) {
                    cateMap.get(TELE).smsCateProcess(basicInfo, sdf);
                }

                if (basicInfo.getIsExpress() == 1 && cateMap.get(EXPS) != null) {
                    cateMap.get(EXPS).smsCateProcess(basicInfo, sdf);
                }

                if (basicInfo.getIsService() == 1 && cateMap.get(SERV) != null) {
                    cateMap.get(SERV).smsCateProcess(basicInfo, sdf);
                }

                if (basicInfo.getIsPayTool() == 1 && cateMap.get(PAYT) != null) {
                    cateMap.get(PAYT).smsCateProcess(basicInfo, sdf);
                }

                if (basicInfo.getIsBank() == 1 && cateMap.get(BANK) != null) {
                    cateMap.get(BANK).smsBankProcess(basicInfo, sdf);
                }

                if (basicInfo.getIsCrdt() == 1 && cateMap.get(CRDT) != null) {
                    cateMap.get(CRDT).smsCrdtProcess(basicInfo, sdf);
                }

                if (basicInfo.getIsItntLend() == 1 && cateMap.get(LOAN) != null) {
                    cateMap.get(LOAN).smsItntProcess(basicInfo, sdf);
                }

                if (basicInfo.getIsOd() == 1 && cateMap.get(OD) != null) {
                    cateMap.get(OD).smsOdProcess(basicInfo, sdf);
                }
            }

        } catch (Exception e) {
            LOG.error("smsCateLabelProcess excep: " + e.toString());
        }
    }

    private static void smsLoanOdProcess(
            SmsInfoBasic basicInfo,
            HashMap<String, SmsCategory> cateMap,
            SimpleDateFormat sdf,
            Integer diffDatys) {
        try {
            int isRecv = basicInfo.getIsRecv();
            String body_name = basicInfo.getBody_name();

            if (isRecv == 1 && body_name != null && body_name.length() >= 2) {
                if (basicInfo.getIsOd() == 1 && cateMap.get(OD) != null) {
                    cateMap.get(OD).smsOdProcess(basicInfo, sdf);
                }
            }

        } catch (Exception e) {
            LOG.error("smsLoanOdProcess excep: " + e.toString());
            LOG.error("smsLoanOdProcess input: " + basicInfo.toString());
        }
    }

    private static JSONObject filterSmsInfoMsg(String value) {
        JSONObject res = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
        try {
            if (value != null && value.contains(MSGTYPE)) {
                JSONObject inputJson = JSONObject.parseObject(value);
                if (inputJson != null) {
                    String type = inputJson.getString("type");
                    if (type != null && type.equals(MSGTYPE)) {
                        JSONObject datajson = inputJson.getJSONObject("dataJson");
                        if (datajson != null) {
                            JSONObject job = datajson.getJSONObject("job");
                            if (job != null) {
                                String job_id = job.getString(INJOBID);
                                if (job_id != null) {
                                    res.put(OUTJOBID, job_id);
                                }
                            }
                            String user_key = datajson.getString(INPUTKEYBY);
                            if (user_key != null) {
                                res.put(OUTPUTKEY, user_key);
                            }
                            JSONObject data = datajson.getJSONObject("data");
                            if (data != null) {
                                JSONObject baseData = data.getJSONObject("baseData");
                                if (baseData != null) {
                                    Long capture_time = baseData.getLong(HTTPTIMESTAMP);
                                    if (capture_time != null) {
                                        res.put(CAPTIME, capture_time);
                                        JSONArray smsInfoList = data.getJSONArray("smsInfoList");
                                        if (smsInfoList != null) {
                                            //                                            JSONArray
                                            // outJsonArray = jsonListFilter(smsInfoList,
                                            // capture_time, sdf);
                                            //                                            if
                                            // (outJsonArray.size() > 0) {
                                            //
                                            // res.put(SMSLIST, outJsonArray);
                                            //                                            }
                                            res.put(SMSLIST, smsInfoList);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            LOG.error(e.toString());
            LOG.error("filterSmsInfoMsg excep input: " + value);
        }
        return res;
    }

    private static JSONArray jsonListFilter(JSONArray input, Long cap_time, SimpleDateFormat sdf) {
        JSONArray res = new JSONArray();
        try {
            int size = input.size();
            for (int i = 0; i < size; i++) {
                JSONObject smsInfo = (JSONObject) input.get(i);
                Integer type = smsInfo.getInteger("type");
                Long date = smsInfo.getLong("date");
                if ((type != null && (type == 1 || type == 2))
                        && (date != null && CommonTimeTools.dateDiff(cap_time, date, sdf) <= 365)) {
                    res.add(smsInfo);
                }
            }

        } catch (Exception e) {
            LOG.error(e.toString());
            LOG.error("jsonListFilter excep input: " + input);
        }
        return res;
    }
}
